package com.swyc.osschat.Test.jiajiemi.rsa;

import com.swyc.osschat.Common.Util.Decode.RSAUtils;

import java.util.Map;

/**
 * @description TODO
 * @Author: z156940l@outlook.com
 * @className Test
 * @Date: 2023/3/21 17:11
 */
public class Test {

    static String publicKey;
    static String privateKey;

    static {
        try {
            Map<String, Object> keyMap = RSAUtils.genKeyPair();
            publicKey = RSAUtils.getPublicKey(keyMap);
            privateKey = RSAUtils.getPrivateKey(keyMap);
            System.err.println("公钥： \n\r" + publicKey);
            System.err.println("私钥： \n\r" + privateKey);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception{

//        pub2pri();

        pri2pub();
    }

    private static void pub2pri() throws Exception {
        System.out.println("公钥加密-私钥解密");
        String source = "这是一段rsa加密文字";
        byte[] data = source.getBytes();
        byte[] encodeData = RSAUtils.encryptByPublicKey(data, publicKey);
        System.out.println("公钥加密文字：" + new String(encodeData));
        byte[] decodeData = RSAUtils.decryptByPrivateKey(encodeData, privateKey);
        System.out.println("私钥解密文字：" + new String(decodeData));
    }

    private static void pri2pub()throws Exception {
        System.out.println("私钥加密-公钥解密");
        String source = "这是另外一段rsa加密文字";
        byte[] data = source.getBytes();
        byte[] encodeData = RSAUtils.encryptByPrivateKey(data, privateKey);
        System.out.println("私钥加密文字：" + new String(encodeData));
        byte[] decodeData = RSAUtils.decryptByPublicKey(encodeData, publicKey);
        System.out.println("公钥解密文字：" + new String(decodeData));

        String sign = RSAUtils.sign(encodeData, privateKey);
        System.out.println("签名：" + sign);
        boolean status = RSAUtils.verify(encodeData, publicKey, sign);
        System.out.println("验证结果：" + status);
    }
}
